require 'models/mud_base'
require 'models/has_many_characters'

class Account < MudBase
  include HasManyCharacters
  
  properties :username, :password, :last_login
  
  
  def initialize(args)
    raise "Missing Required Properties" unless (args.key?(:username) and args.key?(:password))
    raise "Invalid username" unless Account.valid_username?(args[:username])
    raise "Invalid password" unless Account.valid_password?(args[:password])
    
    self.username, self.password = args[:username], args[:password]
    self.last_login = Time.now
    self.save
  end
  
  
  def name
    self.username
  end
  
  def Account.valid_username?(username)
    true
  end
  
  def Account.valid_password?(password)
    true
  end
  
  def Account.exist?(username)
    File.exist? "data/account/#{username}.yaml"
  end
  
  def Account.validate(args)
    account = nil
    file_name = "data/account/#{args[:username]}.yaml"
    
    raise "Missing Required Properties" unless (args.key?(:username) and args.key?(:password) )
    raise "Invalid username" unless Account.exist?(args[:username])
    
    File.open(file_name,'r') do |file|
      account = YAML::load(file)
    end 

    raise "Invalid password" unless account.password == args[:password]
    
    account.last_login = Time.now
    account.save

  end
  
  def to_s 
    "username: #{username}, last_login: #{last_login}"
  end
  
  # horrible hack.. i just couldn't figure out how to overload the method with a module
  # maybe it's the fever...
  def to_yaml_properties
    ['@props', '@characters']
  end

=begin
  def Account.load(username)
    #raise "Missing Required Properties" unless (args.key?(:username) and args.key?(:password) )
    file_name = "data/account/#{username}.yaml"
    File.open(file_name,'r') do |file|
      return YAML::load(file)
    end 
  end
=end

end


